#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#include <iostream>


int main()
{
    int listenfd = socket(AF_INET,SOCK_STREAM,0);
    if(listenfd == -1)
    {
        std::cout << "socket调用失败！" << std::endl;
        close(listenfd);
        exit(-1);
    }


    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_port = htons(9090);
    int n = connect(listenfd,(const struct sockaddr *)&server,sizeof(server));
    if(n == -1)
    {
        std::cout << "connect调用失败！" << std::endl;
        close(listenfd);
        exit(-1);
    }
    
    pollfd fds[2];
    fds[0].fd = 0;
    fds[0].events = POLLIN;
    fds[0].revents = 0;
    fds[1].fd = listenfd;
    fds[1].events = POLLIN | POLLRDHUP;
    fds[1].revents = 0;

    int pipefd[2];
    pipe(pipefd);

    while(true)
    {
        int ret = poll(fds,2,-1);
        if(ret == -1)
        {
            std::cout << "poll调用失败!" << std::endl;
            break;
        }
        if(fds[0].revents & POLLIN)
        {
            splice(0,nullptr,pipefd[1],nullptr,32768,SPLICE_F_MORE | SPLICE_F_MOVE);
            splice(pipefd[0],nullptr,listenfd,nullptr,32768,SPLICE_F_MORE | SPLICE_F_MOVE);
        }
        if(fds[1].revents & POLLIN)
        {
            char buffer[1024] = {0};
            int n = recv(listenfd,buffer,sizeof(buffer)-1,0);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "接收到消息: " << buffer << std::endl;
            }
        }
    } 
    close(listenfd);
    return 0;
}